/*
 * @Author: yanbinbin
 * @Date: 2021-04-21 17:53:05
 * @LastEditTime: 2021-04-22 15:43:53
 * @LastEditors: Please set LastEditors
 * @Description: EventBus 遵循发布/订阅模式，允许订阅者订阅事件，
 * 当发布者触发事件订阅者和发布者之间就可以通过事件交互
 * @FilePath: \inherited_widget\lib\event_bus_page.dart
 */

import 'package:flutter/material.dart';
import 'package:event_bus/event_bus.dart';
import 'dart:async';

class CustomEvent {
  String msg;
  CustomEvent(this.msg);
}

EventBus eventBus = new EventBus();

class FirstPage extends StatefulWidget {
  FirstPage({Key? key}) : super(key: key);

  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  String msg = "通知";
  late StreamSubscription subscription;
  @override
  void initState() {
    //监听CustomEvent事件，刷新UI
    subscription = eventBus.on<CustomEvent>().listen((event) {
      print(event);
      setState(() {
        msg += event.msg;
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Page'),
      ),
      body: Text(msg),
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.push(
            context, MaterialPageRoute(builder: (context) => SecondPage())),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Page"),
      ),
      body: ElevatedButton(
          child: Text('Fire Event'),
          // 触发CustomEvent事件
          onPressed: () => eventBus.fire(CustomEvent("hello"))),
    );
  }
}
